#!/usr/bin/env python3.10

import ftplib
import json
import os
import shutil
import sys
import urllib.request
from zipfile import ZipFile

ftp_host = ''
ftp_login = ''
ftp_pass = ''

def get_client_version():
    try:
        with open('./.minecraft/kubejs/config/client.properties', 'r', encoding="utf-8") as file:
            for line in file.readlines():
                if line.startswith('title'):
                    client_version = line.strip().split()[-1]
        return client_version
    except Exception as e:
        print(e)
    # print(client_version)


def get_server_version(url):
    """return str in description from server"""
    server_url = f'https://api.mcsrvstat.us/2/{url}'
    res = urllib.request.urlopen(server_url).read()
    server_version = json.loads(res)["motd"]["clean"][1]
    # print(server_version)
    return server_version


def _download_files_from_ftp(version):
    ftp = ftplib.FTP(ftp_host)
    ftp.login(ftp_login, ftp_pass)

    ftp_file = f'{version}.zip'
    zip_file = f'{os.getcwd()}/{ftp_file}'
    try:
        print('Starting download ...')
        with open(zip_file, 'wb') as file:
            ftp.retrbinary('RETR ' + ftp_file, file.write)
        print('Download Successful')
        return zip_file
    except Exception as e:
        print(e)


def _collect_files_for_delete(zip) -> tuple:
    zip_files = [file_name.filename for file_name in ZipFile(zip).infolist()]
    to_delete = []
    for i in zip_files:
        try:
            name = i.strip().split('/')[0]
        except:
            name = i
        if name not in to_delete:
            to_delete.append(name)
    return tuple(to_delete)


def _delete_some_trash(files):
    os.chdir('.minecraft')
    for list_dir in os.listdir('./'):
        for i in files:
            if list_dir.lower() == i.lower:
                try:
                    shutil.rmtree(i)
                except NotADirectoryError:
                    os.remove(i)
                except FileNotFoundError:
                    continue
    os.chdir('..')


def _extract_files(zip):
    print(f'Extract {zip}')
    with ZipFile(zip, 'r') as z:
        z.extractall('.minecraft')
    print('Extract successful')
    os.remove(zip)


def update_instance(server_version):
    print(f'Need update to {server_version}')
    file = _download_files_from_ftp(server_version)
    to_delete = _collect_files_for_delete(file)
    _delete_some_trash(to_delete)
    _extract_files(file)


def main():
    os.chdir(sys.argv[1])
    server = get_server_version('modded.mrakells.fun')
    client = get_client_version()
    if client != server:
        update_instance(server)
    else:
        print('Not need update')


if __name__ == '__main__':
    main()
